package cn.emall.controller;

import cn.emall.config.JwtProperties;

import cn.emall.pojo.Cart;
import cn.emall.pojo.Product;
import cn.emall.service.CartService;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import token.common.pojo.UserInfo;
import token.common.util.JwtUtil;
import utils.ResponseBean;
import utils.ResultCode;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Allen_HJL
 * @version 1.0
 * @date 2020/9/13 19:58
 */
@RestController
@RequestMapping("/cart")
@Api(value = "购物车接口")
public class CartController {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private CartService cartService;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getAllCarts")
    @ApiOperation(value = "获得购物车信息", notes = "直接获得")
    public ResponseBean getAllCarts(){
        System.out.println("getAllCarts！！！");
        return ResponseBean.success(ResultCode.FIND_MANYDATA_SUCCESS,cartService.list());
    }

    //购物车应该不需要用分页查询
    //应该只需要一个获得全部购物车信息的接口就行（如上）

    @GetMapping("/addOneCart/{productId}")
    @ApiOperation(value = "加入某件商品进购物车", notes = "根据商品id add, 只允许点击一次，不可以多次点击来增加商品在购物车里的数量")
    public ResponseBean addOneCart(@CookieValue("EMALL_TOKEN") Cookie cookie, @PathVariable int productId) throws Exception {
//        Cookie[] cookie=request.getCookies();
//        System.out.println("++++++++++++++");
//        for(Cookie lo:cookie){
//            System.out.println(lo.getName()+" "+lo.getValue());
//        }
        System.out.println("+++++++++++++++");
        //调用product模块查询该商品的库存

//        String str = restTemplate.getForObject("http://emall-user-service/user/queryUser/"+username+"/"+password,String.class);
//        ResponseBean responseBean=JSON.parseObject(str, ResponseBean.class);
//        if(responseBean.getCode().equals(ResultCode.FIND_DATA_FAILURE)){
//            return null;
//        }
//        User user=JSON.parseObject(responseBean.getData().toString(),User.class);
//
//        return user;
        UserInfo userInfo= JwtUtil.getInfoFromToken(cookie.getValue(),jwtProperties.getPublicKey());

        ResponseBean responseBean = restTemplate.getForObject("http://emall-product-service/product/getOneProductById/"+ productId,ResponseBean.class);
        System.out.println(responseBean.getData());

        if(responseBean.getCode().equals(ResultCode.FIND_DATA_FAILURE)){
            return null;
        }

        Product product = JSON.parseObject(JSON.toJSONString(responseBean.getData()), Product.class);
        if( product.getStock() == 0 || product.getStatus() == 2){  //1为在售  2位下架 3为删除  但删除不会显示出来  而下架会显示
            System.out.println("库存为0 或 商品状态为 下架状态， 不可加入购物车");
            return ResponseBean.failure(ResultCode.ADD_DATA_FAILURE);
        }

        System.out.println(product);

        int userId =  userInfo.getId();
        String userName = userInfo.getUsername();

        Cart cart =  new Cart();
        cart.setCreateTime(new Date());
        cart.setUpdateTime(new Date());

        cart.setUserId(userId);
        cart.setUserName(userName);

        cart.setProductDetail(product.getDetail());
        cart.setProductMain_image(product.getMainImage());
        cart.setProductName(product.getName());
        cart.setProductPrice(product.getPrice());
        cart.setProductSubTitle(product.getSubtitle());
        cart.setQuantity(1);

        cartService.save(cart);

        return ResponseBean.success(ResultCode.ADD_DATA_SUCCESS, cartService.list());
    }

    @GetMapping("/deleteOneCart/{id}")
    @ApiOperation(value = "将某商品移除购物车", notes = "根据购物车主键id进行移除")
    public ResponseBean deleteCart(@PathVariable int id){

        boolean save = cartService.removeById(id);
        if(save  == true ){
            return ResponseBean.success(ResultCode.DELETE_DATA_SUCCESS, cartService.list());
        }else{
            return ResponseBean.failure(ResultCode.DELETE_DATA_FAILURE, cartService.list());
        }

    }

    @GetMapping("/updateCartQuantity/{id}/{quantity}")
    @ApiOperation(value = "更改某商品在购物车的数量", notes = "根据购物车主键id进行更改")
    public ResponseBean updateCartQuantity(@PathVariable int id, @PathVariable int quantity){

        Cart cart = cartService.getById(id);
        if( cart.getQuantity() < quantity ){
            //商品的总数量小于购物车该商品的数量
            return ResponseBean.failure(ResultCode.UPDATE_DATA_FAILURE);
        }else{
            cart.setQuantity(quantity);

            ResponseBean responseBean = restTemplate.getForObject("http://emall-product-service/product/updateProduct/"+ cart.getProductId() + "/" + quantity,ResponseBean.class);
            System.out.println(responseBean.getData());

            if(responseBean.getCode().equals(ResultCode.UPDATE_DATA_FAILURE)){
                return null;
            }
            System.out.println("调用product修改商品库存成功");

            cartService.updateById(cart);

            return ResponseBean.success(ResultCode.UPDATE_DATA_SUCCESS, cart);

        }

    }

}


